import dayjs from "dayjs";
import AsyncStorage from '@react-native-async-storage/async-storage';
import {IM_TOKEN_KEY, token_emu} from "@/constants/index"
import {format, parse, isSameDay, getDay, isValid} from 'date-fns';

export const shouldDisplayTime = (currentMessageTime, previousMessageTime, threshold = 5) => {
    if (!previousMessageTime) {
        return true;
    }

    const diffInMinutes = (currentMessageTime - previousMessageTime) / (1000 * 60);
    // console.log('diffInMinutes', diffInMinutes);
    return diffInMinutes > threshold; // 超过阈值则显示时间
};

export const messageformatDateTime = (inputDate) => {
    const now = dayjs();
    const dateToFormat = dayjs(inputDate);

    // 判断输入时间是否为今天
    if (dateToFormat.isSame(now, 'day')) {
        return dateToFormat.format('HH:mm'); // 只显示小时和分钟
    }

    // 判断输入时间是否在当前月份
    if (dateToFormat.isSame(now, 'month')) {
        return dateToFormat.format('MM-DD HH:mm'); // 显示月份和日期
    }

    // 默认格式显示年份、月份和日期
    return dateToFormat.format('YYYY-MM-DD HH:mm');
};


export const getToken = async function() {
    try {
        const token = await AsyncStorage.getItem(token_emu)

        if (token !== null) {
            console.log('Retrieved value:', token);
            return token;
        } else {
            return null;
        };

    } catch (e) {
        console.error('Failed to fetch data', e);
    }
};

export const setStorgeToken = async function (token) {
    try {
        await AsyncStorage.setItem(token_emu, token)

    } catch (e) {
        console.error('Failed to fetch data', e);
    }
};

export const getIMToken = async function() {
    try {
        const token = await AsyncStorage.getItem(IM_TOKEN_KEY)

        if (token !== null) {
            console.log('Retrieved value:', token);
            return token;
        } else {
            return null;
        };

    } catch (e) {
        console.error('Failed to fetch data', e);
    }
};

export const setImStorgeToken = async function (token) {
    try {
        await AsyncStorage.setItem(IM_TOKEN_KEY, token)

    } catch (e) {
        console.error('Failed to fetch data', e);
    }
};

export const clearStorage = async () => {
    try {
        console.log('zhixing')
        await AsyncStorage.clear();
        await AsyncStorage.setItem(token_emu, "")
        const token = await AsyncStorage.getItem(token_emu)
        console.log('token', token)

    } catch (e) {
        console.error('Failed to clear storage', e);
    }
};


export const hasLogin = function () {
    let flag = false;
    setTimeout(async () => {

        try {
            const token = await AsyncStorage.getItem(token_emu);
            console.log('token', token);
            if (token == null) {
                flag = false
            } else {
                flag = true
            };
        } catch (e) {
            flag = false;
        };
        console.log('flag', flag);
        return flag;
    }, 1000)
    return flag;
};

export const objectToQueryParams = function (obj) {
    return Object.keys(obj)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
        .join('&');
}

export const parseFloat = function (val) {
    const result = (val / 100).toFixed(2);
    return result;
};

export const calculateTotalPages = function (totalItems, itemsPerPage) {
    return Math.ceil(totalItems / itemsPerPage);
}


export const handleDate = function (startDate, endData) {
    const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    if (!isValid(startDate) || !isValid(endData)) return "";

    if (Number(format(endData, "yyyyMd")) == Number(format(startDate, "yyyyMd"))) {
        return daysOfWeek[getDay(endData)] + " " + format(endData, "M")+ "." + format(endData, 'dd')
    } else {
        return daysOfWeek[getDay(startDate)] + " " + format(startDate, "M")+ "." + format(startDate, 'dd') + "-" + daysOfWeek[getDay(endData)] + " " + format(endData, "M")+ "." + format(endData, 'dd');
    };
};


export const validatePhoneNumber = function (phoneNumber) {
    const regex = /^(?:\+?86)?1[3-9]\d{9}$/; // 支持国内手机号格式，包含可选的 "+86"
    return regex.test(phoneNumber);
}
